﻿package controllers.portal;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rbac.models.Oplog;
import rbac.models.Privilege;
import rbac.models.User;
import utils.ImageUtil;

import models.Banner;
import models.Infotype;
import models.Filestore;
import com.et.mvc.BinaryView;
import com.et.mvc.JsonView;
import com.et.mvc.MultipartFile;
import com.et.mvc.TextView;
import com.et.mvc.View;

import com.et.mvc.filter.BeforeFilter;
import com.et.mvc.filter.BeforeFilters;

import controllers.ApplicationController;
import com.et.mvc.MultipartFile;
import com.et.mvc.MultipartRequest;

public class BannerController extends ApplicationController {
	
	public void index() throws Exception{
    	
	}
	
	public View getBannerItems(int page, int rows, String q,int t, String sort, String order) throws Exception {
		String orderBy = "sort";
		if (sort != null && order != null){
			orderBy = sort + " " + order;
		}
		String cond = "1=1";
		List<Object> tmpArgs = new ArrayList<Object>();
		
		/**
		if (t != 0){
			cond += " and (parentId = ?)";
			tmpArgs.add(t);
		}
		
		if (q != null){
			cond += " and (name like '%"+q+"%' or memo like '%"+q+"%' ) ";			
		}
		**/

		Object[] args = tmpArgs.toArray();
		
		long total = Banner.count(Banner.class, cond, args);
		List<Banner> items = Banner.findAll(Banner.class, cond, args, orderBy, rows, (page-1)*rows);
		
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("total", total);
		result.put("rows", items);
		
		return new JsonView(result);
	}
	
	private void uploadFile(Banner item, MultipartFile file)
			throws Exception {
		String fileName = file.getOriginalFilename();

		if (fileName != null && !fileName.equals("")) {
		    //检查是不是图片文件，由于是管理员功能，就不限制文件格式了，这样才可以上传swf文件
			//if (ImageUtil.isImageFile(file) == true)  
			//{
				//删除原来的文件	
			  Filestore store = new Filestore();
			  store.setData(file.getBytes());
			  store.save();
			  if ((item.getFileid() != null) && (!item.getFileid().equals("")))
			  Filestore.execute("delete from Filestores where id = ?", new Object[]{ Integer.parseInt(item.getFileid())});
			  item.setFileid(store.getId().toString());
			  item.save();
			//}
		}
	}
	
	public View saveBanner(Banner item, String[] rids) throws Exception {
		Map<String,Object> result = new HashMap<String,Object>();
		Integer sort = (Integer) Banner.maximum(Banner.class, "sort",
				null, null);
		if (sort == null) {
			sort = 1;
		} else {
			sort += 1;
		}
		item.setSort(sort);
		if (item.save()){
			MultipartRequest req = (MultipartRequest) request;
			MultipartFile multipartFile = req.getFile("picfile");
			uploadFile(item, multipartFile);
			User user = (User) rbac.getCurrentUser();	
			Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")新建横幅，内容为：" + new JsonView(item));
			
			result.put("success", true);
		} else {
			result.put("failure", true);
			result.put("msg", getErrorMsg(item));
		}
		
		View view = new JsonView(result);
		view.setContentType("text/plain;charset=utf-8");
		return view;
	}
	
	public View updateBanner(int id, Map<String,Object> params, String[] rids) throws Exception {
		Map<String,Object> result = new HashMap<String,Object>();
		User user = (User) rbac.getCurrentUser();
		Banner item = Banner.find(Banner.class, id);
		JsonView olditem= new JsonView(item);
		item = Banner.updateModel(item, params);
		if (item.save()){
			MultipartRequest req = (MultipartRequest) request;
			MultipartFile multipartFile = req.getFile("picfile");
			uploadFile(item, multipartFile);
			Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")修改横幅，原内容为："+ olditem + "\r\n修改内容为：" + new JsonView(item));										

			result.put("success", true);
		} else {
			result.put("failure", true);
			result.put("msg", getErrorMsg(item));
		}
		
		View view = new JsonView(result);
		view.setContentType("text/plain;charset=utf-8");
		return view;
	}
	
	public View destroyBanner(int id) throws Exception {
		Banner item = Banner.find(Banner.class, id);
		User user = (User) rbac.getCurrentUser();				
		Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")删除横幅，内容为：" + new JsonView(item));									

		item.destroy();
		return new JsonView("success:true");
	}
	
	public View move(int id, String dir) throws Exception {
		Banner item = Banner.find(Banner.class, id);
		Banner target = null;
		if (dir.equals("down")) {
			target = Banner.findFirst(Banner.class, "sort>?",
					new Object[] { item.getSort() },
					"sort asc");
		} else {
			target = Banner.findFirst(Banner.class, "sort<? ",
					new Object[] { item.getSort() },
					"sort desc");
		}
		if (target != null) {
			Integer tmp = target.getSort();
			target.setSort(item.getSort());
			target.save();
			item.setSort(tmp);
			item.save();
		}
		return new JsonView("success:true");
	}
	
}
